package com.socialrss.utils.twitter;

import java.util.ArrayList;

import twitter4j.Friendship;
import twitter4j.IDs;
import twitter4j.ResponseList;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.conf.ConfigurationBuilder;

import com.socialrss.accounts.AccountOwner;
import com.socialrss.accounts.FollowedPerson;
import com.socialrss.constants.SocialNetworkNames.SocialNetKeys;
import com.socialrss.utils.SocialRssModel;
import com.socialrss.utils.foursquarekit.FoursquareConstants;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class TwitterFriendsThread extends AsyncTask<String, String, ArrayList<FollowedPerson>>{

//	private Activity activity;
//	// Progress dialog
//	ProgressDialog pDialog;
	ArrayList<FollowedPerson> followers;
//	public TwitterFriendsThread( Activity activity) {
//		this.activity = activity;
//	}
	/**
	 * Before starting background thread Show Progress Dialog
	 * */
//	@Override
//	protected void onPreExecute() {
//		super.onPreExecute();
//		pDialog = new ProgressDialog(activity);
//		pDialog.setMessage("Getting Friend List...");
//		pDialog.setIndeterminate(false);
//		pDialog.setCancelable(false);
//		pDialog.show();
//	}

	/**
	 * getting Places JSON
	 * */
	protected ArrayList<FollowedPerson> doInBackground(String... args) {
		//Log.d("Tweet Text", "> " + args[0]);
		//String status = args[0];
		try {
			ConfigurationBuilder builder = new ConfigurationBuilder();
			builder.setOAuthConsumerKey(TwitterUtil.TWITTER_CONSUMER_KEY);
			builder.setOAuthConsumerSecret(TwitterUtil.TWITTER_CONSUMER_SECRET);
			AccountOwner owner = SocialRssModel.Instance(null).getAccessTokenOfSocialNet(SocialNetKeys.tw.toString());
			// Access Token
			String access_token = owner.getAccessToken();
			// Access Token Secret
			String access_token_secret = owner.getSecret_token();
			
			AccessToken accessToken = new AccessToken(access_token, access_token_secret);
			Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
			// Get friend list
			//twitter4j.Status response = twitter.updateStatus(status);
			long cursor = -1;
			IDs ids;
			followers = new ArrayList<FollowedPerson>();
			do {
				ids = twitter.getFriendsIDs(cursor);
				
				ResponseList<Friendship> friendships = twitter.lookupFriendships(ids.getIDs());
	            for (Friendship friendship : friendships) {
	            	if(friendship.isFollowing()) {
	            		FollowedPerson user = new FollowedPerson(0, friendship.getScreenName(), SocialNetKeys.tw, 0, String.valueOf(friendship.getId()));
	            		followers.add(user);
	            	}
	                System.out.println("@" + friendship.getScreenName()
	                        + " following: " + friendship.isFollowing()
	                        + " followed_by: " + friendship.isFollowedBy());
	            }
			} while ((cursor = ids.getNextCursor()) != 0);
			
			//Log.d("Status", "> " + response.getText());
		} catch (TwitterException e) {
			// Error in updating status
			Log.d("Twitter Update Error", e.getMessage());
		}
		return followers;
	}

	/**
	 * After completing background task Dismiss the progress dialog and show
	 * the data in UI Always use runOnUiThread(new Runnable()) to update UI
	 * from background thread, otherwise you will get error
	 * **/
	protected void onPostExecute(ArrayList<FollowedPerson>  mylist) {
		SocialRssModel.Instance(null).insertListOfConnections((FollowedPerson[]) mylist.toArray(), SocialNetKeys.tw);
		Log.i("Twitter Utils Info", "Twitter followings are inserted into database.");
		// dismiss the dialog after getting all products
//		pDialog.dismiss();
//		// updating UI from Background Thread
//		activity.runOnUiThread(new Runnable() {
//			@Override
//			public void run() {
//				Toast.makeText(activity.getApplicationContext(),
//						"Friendlist fetched successfully", Toast.LENGTH_SHORT)
//						.show();
//			}
//		});
	}

}

